<?php


namespace Aoe\Emulator\Schema\Element;


use Aoe\Emulator\Ifc\Key;
use Aoe\Emulator\Schema\Model;
use Exception;

/**
 * # 外键
 */
class Relation extends Element
{
    /**
     * @var ?Model
     */
    protected ?Model $relation_model = null;
    
    protected ?string $relation_name = null;
    
    public function isRelation(): bool
    {
        return true;
    }
    
    /**
     * @throws Exception
     */
    public function getRelateModel(): Model
    {
        if (!$this->relation_model) {
            $this->relation_model = $this->model->getModel(
                $this->getRelationName(),
            );
        }
        
        return $this->relation_model;
    }
    
    public function getRelationName(): string
    {
        if ($this->relation_name === null) {
            $name                = $this->get(Key::RELATION, true);
            $this->relation_name = ($name === true) ? $this->name : $name;
        }
        
        return $this->relation_name;
    }
}